<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\DictService;

class DictLogic extends BackendLogic
{
    public function __construct()
    {
        $this->service = Container::get(DictService::class);
    }

    /**
     * 获取列表
     * @return array
     */
    public function getList(): array
    {
        $configList = $this->service->getList([['mark', '=', 1]], ['*'], ['sort' => 'asc']);
        return message($configList);
    }

    /**
     * 编辑字典项
     * @return array
     */
    public function edit(): array
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['name'])) throw new ApiException('请输入名称');
        if (empty($data['code'])) throw new ApiException('请输入值');
        if (empty($data['sort'])) throw new ApiException('请输入排序');
        $save['name'] = trim($data['name']);
        $save['sort'] = $data['sort'];
        $save['code'] = $data['code'];
        $save['note'] = $data['note']??'';
        unset($data['id']);
        if ($id == 0) {
            // code重复性验证
            $count = $this->service->getUserCountByWhere([["code", '=', $save['code']], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的值');
            $this->service->add($save);
        } else {
            $count = $this->service->getUserCountByWhere([["code", '=', $save['code']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的值');
            $this->service->save($save, $id);
        }
        return message();

    }

}
